package top.jlzhou.boot.config;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.servlet.support.RequestContext;

import com.fasterxml.jackson.databind.ObjectMapper;

import lombok.extern.slf4j.Slf4j;
import top.jlzhou.CodeException;
import top.jlzhou.R;


/**
 * 
 * @ClassName	LoginFilter
 * @Description	TODO(登录状态过滤器)
 * @author	J.L.Zhou
 * @date	2019年2月21日 下午5:40:45
 * @version 	V1.0
 * @Copyright	2019 PEPay Inc. All rights reserved. 
 * 	注意：本内容仅限于公司内部传阅，禁止外泄以及用于其他的商业目
 */
@Component
@Slf4j
public class LoginFilter implements Filter {
	
	@Autowired
	private ObjectMapper mapper;

	
	
	private final static String BEARER = "Bearer ";
	public static final String LOGIN_INFO_KEY = "LOGIN_INFO";

	@Override
	public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain arg2)
			throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest)arg0;
		HttpServletResponse response = (HttpServletResponse)arg1;
		
		WebApplicationContext w = WebApplicationContextUtils.getWebApplicationContext(request.getServletContext());
		request.setAttribute(RequestContext.WEB_APPLICATION_CONTEXT_ATTRIBUTE, w);
		String token = request.getHeader("Authorization");
		RequestContext rc = new RequestContext(request);
		if(token==null){
			outJSON(response,R.error(12, rc.getMessage("code.12","未设置header-Authorization")));
//			outJSON(response,R.error(12, "未设置header-Authorization"));
			return;
		}
		if(!token.startsWith(BEARER)){
			outJSON(response,R.error(13, rc.getMessage("code.13","Authorization格式不正确")));
//			outJSON(response,R.error(13, "Authorization格式不正确"));
			return;
		}
		token = token.substring(7);
		log.debug("token:{}",token);
		try{
//			request.setAttribute(LOGIN_INFO_KEY, service.getByToken(token));
			arg2.doFilter(arg0, arg1);
		}catch(CodeException ex){
			outJSON(response,R.error(ex.getCode(), rc.getMessage("code."+ex.getCode(),"未知异常")));
//			outJSON(response,R.error(ex.getCode(), "未知异常"));
			return;
		}
	}
	
	private void outJSON(HttpServletResponse response,R r)throws ServletException, IOException{
		response.setContentType("text/plain;charset=UTF-8");
		response.getWriter().print(mapper.writeValueAsString(r));
		response.flushBuffer();
	}
	


}
